package com.zc.framework.datasource;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.util.Assert;

import java.util.Stack;

/**
 * Created by zc on 2016/8/30.
 */
public class DataSourceContextHolder {

    private static Logger logger = LogManager.getLogger(DataSourceContextHolder.class);

    private static ThreadLocal<Stack<String>> DS_CTX_STACK_HOLDER = new ThreadLocal() {
        protected Stack<String> initialValue() {
            return new Stack();
        }
    };

    public DataSourceContextHolder() {
    }

    public static void setDataSource(String dataSource) {
        Assert.notNull(dataSource, "dataSource cannot be null");
        Stack ctxStatck = (Stack)DS_CTX_STACK_HOLDER.get();
        ctxStatck.push(dataSource);
        logger.debug("Stack \'After Push DataSource\' Count {{}}", new Object[]{Integer.valueOf(ctxStatck.size())});
    }

    public static String getDataSource() {
        Stack ctxStatck = (Stack)DS_CTX_STACK_HOLDER.get();
        if(ctxStatck == null) {
            DS_CTX_STACK_HOLDER.remove();
            ctxStatck = (Stack)DS_CTX_STACK_HOLDER.get();
        }

        return ctxStatck.isEmpty()?null:(String)ctxStatck.peek();
    }

    public static void clearDataSource() {
        Stack ctxStack = (Stack)DS_CTX_STACK_HOLDER.get();
        logger.debug("Stack \'Before POP DataSource\' Size {{}}", new Object[]{Integer.valueOf(ctxStack.size())});
        if(ctxStack != null && !ctxStack.isEmpty()) {
            ctxStack.pop();
        }

    }
}
